import { ENV, HttpError, Request, Response, Router, SERVER_CALL, useTransaction } from "@sker/core";
import { join } from "path";
import { DependencyContainer } from "tsyringe";
import { existsSync } from 'fs-extra'
import { SysAddon } from "@sker/entities";
declare const injector: DependencyContainer;
export interface TemplateOptions {
    isDev?: boolean;
    title?: string;
    description?: string;
    keywords?: string;
    config?: any;
    [key: string]: any;
    injector?: DependencyContainer;
}
export function useTemplate(options: TemplateOptions = {}, send: boolean = true) {
    return new Promise(async (resolve, reject) => {
        const _injector = options.injector || injector;
        const serverCall = _injector.resolve(SERVER_CALL)
        if(serverCall) return resolve(`server call data`)
        const env = _injector.resolve(ENV)
        const req = _injector.resolve(Request)
        const res = _injector.resolve(Response)
        const router: Router = Reflect.get(req, 'router')
        const root = router?.root || process.cwd();
        const { scope, addon, controller, platform, action } = router || {};
        const addonSetting = await useTransaction(async m => {
            const sysAddon = await m.findOne(SysAddon, { where: { name: `@${scope}/${addon}` }, select: { setting: true } })
            return sysAddon?.setting;
        })
        const settingJson = join(root, 'data/setting.json')
        let setting: any = {};
        if(existsSync(settingJson)){
            setting = require(settingJson)
        }
        options = { dev: env.dev, ...setting, ...options }
        const SERVER_DATA = JSON.stringify({ ...options, addon: addonSetting })
        options.SERVER_DATA = SERVER_DATA;
        if (!scope || !addon) throw new HttpError(`参数错误: ${scope}/${addon}`);
        const templateDir = join(root, 'addons', `@${scope}`, addon, 'dist/public', platform || 'web');
        let htmlFile: string = ``
        const canUseHtml: string[] = [];
        if (controller && action) {
            htmlFile = join(templateDir, controller, `${action}.html`)
            canUseHtml.push(htmlFile)
            if (existsSync(htmlFile)) {
                res.render(htmlFile, options, (err, html) => {
                    if (err) return reject(err)
                    if (send) res.type('html').send(html)
                    resolve(html)
                })
                return;
            }
            htmlFile = join(templateDir, `${controller}.html`)
            canUseHtml.push(htmlFile)
            if (existsSync(htmlFile)) {
                res.render(htmlFile, options, (err, html) => {
                    if (err) return reject(err)
                    if (send) res.type('html').send(html)
                    resolve(html)
                })
                return;
            }
        }
        if (controller) {
            htmlFile = join(templateDir, `${controller}.html`)
            canUseHtml.push(htmlFile)
            if (existsSync(htmlFile)) {
                res.render(htmlFile, options, (err, html) => {
                    if (err) return reject(err)
                    if (send) res.type('html').send(html)
                    resolve(html)
                })
                return;
            }
        }
        htmlFile = join(templateDir, 'index.html')
        canUseHtml.push(htmlFile)
        if (existsSync(htmlFile)) {
            res.render(htmlFile, options, (err, html) => {
                if (err) return reject(err)
                if (send) res.type('html').send(html)
                resolve(html)
            })
            return;
        }
        reject(new HttpError(`没有找到模板 ${canUseHtml.join('\n')}`))
    })
}